import { Link, history, useIntl, useSelector, useDispatch } from 'umi';
import styles from './header.less';
import { Input, Button, Space, Menu, Dropdown } from 'antd';
import { SettingOutlined, DownOutlined, UserOutlined } from '@ant-design/icons';
import { useState, useEffect } from 'react';

import SelectLocale from './selectLocale';
import request from '@/utils/request';

import imgLogo from '@/images/logo.svg';
import { handleAvatarError } from '@/utils';

const settingsRoute = '/settings/generalinfo';

let getstatustimer: any

const onSettings = () => {
  history.replace(settingsRoute);
};

const onSignout = () => {
  request.get('/user/clearToken').then((res) => {
    localStorage.removeItem('token');
    localStorage.removeItem('uid');
    localStorage.removeItem('userinfo');
    history.replace('/login');
  });
};

const Header = function () {
  const intl = useIntl();
  const dispatch = useDispatch();
  const { pathname } = history.location;
  let navSelected = 0;
  if (pathname) {
    if (['/inbox'].includes(pathname)) {
      navSelected = 1;
    } else if (['/contacts'].includes(pathname)) {
      navSelected = 2;
    } else if (['/roster'].includes(pathname)) {
      navSelected = 3;
    } else if (['/campaigns'].includes(pathname)) {
      navSelected = 4;
    }
  }

  let userInfo = {};
  try {
    userInfo = JSON.parse(localStorage.getItem('userinfo'));
  } catch (error) {}
  
  useEffect(() => {
    getUserStatus()
  }, [])
  // const userInfo = useSelector(
  //   (state) => state.user.userInfo,
  // );

  const [userStatus, setUserStatus] = useState('')

  const userMenu = () => {
    return (
      <Menu>
        <Menu.Item>
          <div className={styles.dropdownItem} onClick={onSettings}>
            {intl.formatMessage({ id: 'settings' })}
          </div>
        </Menu.Item>
        <Menu.Item>
          <div className={styles.dropdownItem} onClick={onSignout}>
            {intl.formatMessage({ id: 'signout' })}
          </div>
        </Menu.Item>
      </Menu>
    );
  };

  const handleOpenInviteUsers = () => {
    history.push('/settings/usermanagement');
    dispatch({ type: 'system/changeIUVisible', visible: true });
  };

  const getUserStatus = () => {
    clearTimeout(getstatustimer)
    request.get('/user/status').then((res) => {
      setUserStatus(res.data.authenticated)
      getstatustimer = setTimeout(() => {
        getUserStatus()
      }, 60 * 1000)
    }).catch(err => {
      getstatustimer = setTimeout(() => {
        getUserStatus()
      }, 60 * 1000)
    })
  }

  const handleReconnectWhatas = () => {
    request.post('/user/takeover').then((res) => {
      getUserStatus()
    })
  }

  return (
    <div className={styles.header}>
      <div className={styles.main}>
        <div className={styles.left}>
          <div className={styles.logo}>
            <img src={imgLogo} alt="" className={styles.logoImg} />
          </div>
          <div className={styles.menus}>
            <div
              className={`${styles.menuItem} ${
                navSelected === 1 && styles.selected
              }`}
            >
              <Link className={styles.a} to="/inbox">
                {intl.formatMessage({ id: 'inbox' })}
              </Link>
            </div>
            <div
              className={`${styles.menuItem} ${
                navSelected === 2 && styles.selected
              }`}
            >
              <Link className={styles.a} to="/contacts">
                {intl.formatMessage({ id: 'contacts' })}
              </Link>
            </div>
            <div
              className={`${styles.menuItem} ${
                navSelected === 3 && styles.selected
              }`}
            >
              <Link className={styles.a} to="/roster">
                {intl.formatMessage({ id: 'roster' })}
              </Link>
            </div>
            <div
              className={`${styles.menuItem} ${
                navSelected === 4 && styles.selected
              }`}
            >
              <Link className={styles.a} to="/campaigns">
                {intl.formatMessage({ id: 'campaigns' })}
              </Link>
            </div>
          </div>
        </div>
        <div className={styles.center}>
          {/* <Search
            placeholder={intl.formatMessage({ id: 'search' })}
            onSearch={onSearch}
            style={{ width: 200 }}
          /> */}
        </div>
        <div className={styles.right}>
          {/* <Button onClick={handleOpenInviteUsers}>
            {intl.formatMessage({ id: 'inviteusers' })}
          </Button> */}
          {userStatus === 'L' ? <Button onClick={handleReconnectWhatas}>
            {intl.formatMessage({ id: 'reconeectWhatas' })}
          </Button> : null} 
          <div className={styles.set}>
            <Link to={settingsRoute}>
              <SettingOutlined style={{ fontSize: 18, color: ' #3c4257' }} />
            </Link>
          </div>
          <SelectLocale />
          <Dropdown overlay={userMenu()} className={styles.user}>
            <div
              className={styles.dropdownItem}
              onClick={(e) => e.preventDefault()}
            >
              <img
                src={userInfo.avatar || ''}
                alt=""
                onError={handleAvatarError}
                className={styles.avatar}
              />
              <span className={styles.username}>{userInfo.name}</span>
              <DownOutlined />
            </div>
          </Dropdown>
        </div>
      </div>
    </div>
  );
};

export default Header;
